<template>
	<view>
		<u-toast ref="uToast" /><u-no-network></u-no-network>
		<u-navbar title="商品上架" safeAreaInsetTop fixed placeholder>
			<view class="coreshop-navbar-left-slot" slot="left">
				<u-icon name="arrow-left" size="19" @click="goNavigateBack"></u-icon>
				<u-line direction="column" :hairline="false" length="16" margin="0 8px"></u-line>
				<u-icon name="home" size="22" @click="goHome"></u-icon>
			</view>
			<view slot="right">
			</view>
		</u-navbar>
		<view class="content">
			<view class="coreshop-tabbar-height">
				<view class='img-list'>
					<!-- <view v-for="item in info.items" :key="item.id"> -->
					<view class="coreshop-bg-white coreshop-card-box coreshop-margin-10">
						<view class="coreshop-card-view coreshop-order-view">
							<view class="coreshop-font-md coreshop-text-bold coreshop-text-black">商品信息</view>
							<u-line color="#eee" border-style="dashed" margin="10px 0" />
							<view class="evaluate-c-f">
								<text @click="show = true">{{finalAddress == '' ? "请选择商品类别": finalAddress}}</text>
								<u-picker :show="show" ref="uPicker" :columns="columns" @confirm="sureChoose"
									@cancel="cancelChoose" @change="changeHandler"></u-picker>
							</view>
						</view>


						<view class="coreshop-card-view coreshop-order-view">
							<view class="coreshop-font-md coreshop-text-bold coreshop-text-black">商品名称</view>
							<u-line color="#eee" border-style="dashed" margin="10rpx 0" />
							<view class="evaluate-c-f">
								<input v-model="name" placeholder="名称" />
							</view>
						</view>

						<view class="coreshop-card-view coreshop-order-view">
							<view class="coreshop-font-md coreshop-text-bold coreshop-text-black">商品规格</view>
							<u-line color="#eee" border-style="dashed" margin="10rpx 0" />
							<view class="evaluate-c-f" style="height: auto;">
								<button class="custom-style" @click="funAddSku">{{goodsSkuValues==''?'添加':'编辑'}}</button>
								<view class="mess" style="font-size: 22rpx;">{{goodsSkuValues}}</view>
							</view>
						</view>

						<view class="coreshop-card-view coreshop-order-view">
							<view class="coreshop-font-md coreshop-text-bold coreshop-text-black">计量单位</view>
							<u-line color="#eee" border-style="dashed" margin="10rpx 0" />
							<view class="evaluate-c-f">
								<input v-model="unit" placeholder="单位" />
							</view>
						</view>

						<view class="coreshop-card-view coreshop-order-view">
							<view class="coreshop-font-md coreshop-text-bold coreshop-text-black">成本价</view>
							<u-line color="#eee" border-style="dashed" margin="10rpx 0" />
							<view class="evaluate-c-f">
								<input v-model="costprice" type="digit" inputmode="decimal" placeholder="成本价" />
							</view>
						</view>

						<view class="coreshop-card-view coreshop-order-view">
							<view class="coreshop-font-md coreshop-text-bold coreshop-text-black">销售价</view>
							<u-line color="#eee" border-style="dashed" margin="10rpx 0" />
							<view class="evaluate-c-f">
								<input v-model="price" type="digit" inputmode="decimal" placeholder="销售价" />
							</view>
						</view>

						<view class="coreshop-card-view coreshop-order-view">
							<view class="coreshop-font-md coreshop-text-bold coreshop-text-black">市场价</view>
							<u-line color="#eee" border-style="dashed" margin="10rpx 0" />
							<view class="evaluate-c-f">
								<input v-model="mktprice" type="digit" inputmode="decimal" placeholder="这里录入市场价" />
							</view>
						</view>

						<view class="coreshop-card-view coreshop-order-view">
							<view class="coreshop-font-md coreshop-text-bold coreshop-text-black">商品描述</view>
							<u-line color="#eee" border-style="dashed" margin="10px 0" />
							<view class="evaluate-c-t">
								<textarea v-model="brief" placeholder="这里录入商品描述" />
							</view>
						</view>
						<!-- <view class="coreshop-card-view coreshop-order-view">
							<view class="coreshop-font-md coreshop-text-bold coreshop-text-black">
								商品图片（可上传{{maxUploadImg}}张）</view>
							<u-line color="#eee" border-style="dashed" margin="10px 0" />
							<view class="evaluate-c-b">
								<view class="goods-img-item" v-if="images.length" v-for="(img, key) in images"
									:key="key">
									<image class="del" src="/static/images/common/del.png" mode=""
										@click="removeImg(key)"></image>
									<image class="" :src="img" mode="" @click="clickImg(img)"></image>
								</view>
								<view class="upload-img" v-show="isupload">
									<image class="icon" src="/static/images/common/camera.png" mode=""
										@click="uploadImg()"></image>
									<view class="">拍照上传</view>
								</view>
							</view>
						</view> -->

						<view class="coreshop-card-view coreshop-order-view">
							<view class="coreshop-font-md coreshop-text-bold coreshop-text-black">
								商品图片（可上传{{maxUploadImg}}张）</view>
							<u-line color="#eee" border-style="dashed" margin="10px 0" />
							<view class="evaluate-c-b">
								<u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1"
									multiple :maxCount="5"></u-upload>
							</view>
						</view>

						<view class="coreshop-card-view coreshop-order-view">
							<view class="coreshop-font-md coreshop-text-bold coreshop-text-black"></view>
							<view class="evaluate-c-t">
							</view>
						</view>

					</view>
					<!--                    </view> -->
				</view>
			</view>
		</view>
		<view class="coreshop-foot-hight-view" />
		<view class="coreshop-bg-white coreshop-footer-fixed coreshop-foot-padding-bottom coreshop-padding-5">
			<u-button type="error" size="normal" @click="toSubmit" :disabled='submitStatus'
				:loading='submitStatus'>商品上架</u-button>

		</view>
		<!-- 登录提示 -->
		<!-- <coreshop-login-modal></coreshop-login-modal> -->
	</view>

</template>

<script>
	export default {

		data() {
			return {
				customStyle: {
					width: '100rpx',
					color: '#fff',
					backgroundColor: '#ff0000'
				},
				mode: 'single-column',
				defaultSelector: [0],
				name: '', //采集人员名称
				specs: '', //事件描述
				unit: '',
				price: '0',
				mktprice: '0',
				costprice: '0',
				brief: '',
				image: '',
				goodsType: '',
				goodsCategoryId: '0',
				goodsCategory: '',
				selectShow: true,
				selectList: ['T', 'F'],

				show: false,
				columns: [
					[],
					[]
				],
				columnData: [
					[],
					[],
					[],
					[],
					[],
					[],
					[],
					[],
					[],
					[],
					[],
					[],
					[],
					[],
					[]
				],
				finalAddress: '',

				orderId: 0,
				info: {}, // 订单详情
				images: [],
				score: [], // 商品评价
				textarea: [], // 商品评价信息
				isupload: [], // 启/禁用 图片上传按钮
				rate: 5,
				submitStatus: false,

				goodsSkuIds: '',
				goodsSkuValues: '',
				products: '',

				fileList1: [],
			}
		},
		onLoad(options) {
			this.categories();
			// let userToken = this.$db.get("userToken");
			// console.log(userToken);

			// 监听B页面发送的事件
			this.$eventBus.$on('saveData', (data) => {
				this.goodsSkuIds = data.goodsSkuIds;
				this.goodsSkuValues = data.goodsSkuValues;
				this.products = data.products;
				this.list_sku = data.list_sku;
				this.count_sku = data.count_sku;

				if (this.price == '0') {
					var list_products = JSON.parse(this.products);
					this.price = list_products[0].price;
				}
				if (this.mktprice == '0') {
					var list_products = JSON.parse(this.products);
					this.mktprice = list_products[0].mktprice;
				}
				if (this.costprice == '0') {
					var list_products = JSON.parse(this.products);
					this.costprice = list_products[0].costprice;
				}

				console.log('data:' + JSON.stringify(data));
				console.log('goodsSkuIds:' + this.goodsSkuIds);
				console.log('goodsSkuValues:' + this.goodsSkuValues);
				console.log('products:' + this.products);
			})
		},
		onShow() {

		},
		onUnload() {
			// 页面卸载时移除事件监听，防止内存泄漏
			this.$eventBus.$off('saveData')
		},
		computed: {
			// 获取vuex中状态
			maxUploadImg() {
				return this.$store.state.config.imageMax
				//return 9
			}
		},
		methods: {
			//选择商品类别
			sureChoose(e) {
				this.show = false
				this.finalAddress = e.value[0] + '/' + e.value[1]
				this.goodsType = e.value[1]
				this.goodsCategory = e.value[1]
				console.log(e)

			},
			//关闭商品类别
			cancelChoose(e) {
				this.show = false
				console.log(e)
			},

			// 选择商品类型回调
			selectConfirm(e) {
				this.goodsType = '';
				this.goodsCategoryId = '0';
				e.map((val, index) => {
					this.goodsType += this.goodsType == '' ? val.label : '-' + val.label;
					this.goodsCategoryId = val.value;
				})
			},

			categories() {
				this.$u.api.categories().then(res => {
					if (res.status) {
						this.tabbar = res.data;

						//console.log(res.data);

						res.data.forEach((item, key) => {

							let model = {
								ItemId: key,
								value: item.id,
								label: item.name
							}
							this.columns[0].push(item.name);

							//console.log("key:" + key);

							item.child.forEach((item1, key1) => {

								if (key == 0) {
									this.columns[1].push(item1.name);
								}

								//console.log(this.columns[1]);								

								this.columnData[key].push(item1.name);

							})

						})
					}
				});
			},

			childscategories() {
				this.$u.api.childscategories().then(res => {
					if (res.status) {
						//this.selectList = res.data;
						res.data.forEach((item, key) => {
							let model = {
								ItemId: key,
								value: item.id,
								label: item.name
							}
							this.address[0].push(item.name);
						})

					}
				});
			},

			changeHandler(e) {
				const {
					columnIndex,
					value,
					values, // values为当前变化列的数组内容
					index,
					// 微信小程序无法将picker实例传出来，只能通过ref操作
					picker = this.$refs.uPicker
				} = e
				// 当第一列值发生变化时，变化第二列(后一列)对应的选项
				if (columnIndex === 0) {
					// picker为选择器this实例，变化第二列对应的选项
					picker.setColumnValues(1, this.columnData[index])
				}
			},

			// 获取订单详情
			orderInfo() {
				let data = {
					id: this.orderId
				}

				this.$u.api.orderDetail(data).then(res => {
					if (res.status && res.data.payStatus >= 2 && res.data.shipStatus >= 3 && res.data
						.confirmStatus >= 2 && res.data.isComment === false) {
						const _info = res.data
						let images = []
						let textarea = []
						let upload = []
						let score = []
						_info.items.forEach(item => {
							images[item.id] = []
							textarea[item.id] = ''
							upload[item.id] = true
							score[item.id] = 5
						})
						this.info = _info
						this.images = images
						this.textarea = textarea
						this.score = score
						this.isupload = upload
					} else {
						this.$u.toast('订单不存在或状态不可评价!')
					}
				})
			},


			// 上传图片
			uploadImg() {
				this.$upload.uploadFiles(null, res => {
					if (res.status) {
						//this.images[key].push(res.data.src + '?x-oss-process=image/resize,m_lfit,h_200,w_200')
						this.images.push(res.data.src)
						this.$refs.uToast.show({
							title: res.msg,
							type: 'success',
							back: false
						})
					} else {
						this.$u.toast(res.msg)
					}
				})
			},


			// 删除图片
			removeImg(key) {
				this.images.splice(key, 1)
			},
			// 图片点击放大
			clickImg(img) {
				// 预览图片
				uni.previewImage({
					urls: img.split()
				});
			},

			// 提交
			toSubmit() {
				let _this = this;
				this.submitStatus = true;
				let items = [];
				let _str = '';
				
				// console.log(_this.fileList1);
				// return;

				this.images.forEach((item, key) => {
					let model = {
						orderItemId: key,
						images: item,
						score: _this.score[key],
						textarea: _this.textarea[key]
					}
					items.push(model);
				})

				// for (var k = 0; k < _this.images.length; k++) {
				// 	_str += _this.images[k] + ","
				// }
				// _str = _str.substring(0, _str.lastIndexOf(','));
				
				for (var k = 0; k < _this.fileList1.length; k++) {
					_str += _this.fileList1[k].url + ","
				}
				_str = _str.substring(0, _str.lastIndexOf(','));

				if (_this.finalAddress == '') {
					_this.$u.toast('请选择商品分类！')
					_this.submitStatus = false;
					return false
				}

				if (_this.name == '') {
					this.$u.toast('请输入商品名称！')
					_this.submitStatus = false;
					return false
				}

				//判断商品规格
				if (_this.goodsSkuIds == '') {
					this.$u.toast('请添加商品规格！')
					_this.submitStatus = false;
					return false
				}
				
				//判断图片
				if (_this.fileList1.length <= 0) {
					this.$u.toast('请上传图片！')
					_this.submitStatus = false;
					return false
				}

				let data = {
					//orderId: _this.orderId,
					//items: items
					name: _this.name,
					specs: _this.specs,
					unit: _this.unit,
					price: _this.price,
					mktprice: _this.mktprice,
					costprice: _this.costprice,
					brief: _this.brief,
					images: _str,
					image: _this.fileList1[0].url,
					goodsCategoryId: _this.goodsCategoryId,
					goodsCategory: _this.goodsCategory,
					goodsSkuIds: _this.goodsSkuIds,
					goodsSkuValues: _this.goodsSkuValues,
					products: _this.products
				}
				console.log(data);

				this.$u.api.GoodsGrounding(data).then(res => {
					if (res.code == 0) {
						_this.submitStatus = false;
						//this.$refs.uToast.show({ title: '上架成功', type: 'success', back: true })
						this.$refs.uToast.show({
							message: '上架成功',
							type: 'success',
							complete: function() {
								uni.navigateBack({
									delta: 1
								});
							}
						})

					} else {
						_this.$u.toast(res.msg)
					}
				});
			},
			//添加规格
			funAddSku() {
				this.$u.route({
					url: '/pages/member/goods/goodGrounding/groundingProduct',
					params: {
						products: this.products,
						list_sku: this.list_sku,
						count_sku: this.count_sku
					}
				});
			},

			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1);
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file);
				let fileListLen = this[`fileList${event.name}`].length;
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: "uploading",
						message: "上传中",
					});
				});
				console.log(lists);
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url);
					let item = this[`fileList${event.name}`][fileListLen];
					this[`fileList${event.name}`].splice(
						fileListLen,
						1,
						Object.assign(item, {
							status: "success",
							message: "",
							url: result,
						})
					);
					fileListLen++;
				}
			},
			uploadFilePromise(url) {
				var _this = this;
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: 'https://pb.milane.com.cn/Api/Common/UploadImages', // 仅为示例，非真实的接口地址
						filePath: url,
						name: "file",
						header: {
							'Accept': 'application/json',
							'Content-Type': 'multipart/form-data',
							'Authorization': 'Bearer ' + uni.getStorageSync('userToken')
						},
						formData: {
							user: "test",
						},
						success: (res) => {
							setTimeout(() => {
								resolve(JSON.parse(res.data).data.fileUrl);
							}, 1000);
						},
					});
				});
			},



		},


		watch: {
			images: {
				handler() {
					this.images.forEach((item, key) => {
						this.isupload[key] = item.length >= this.maxUploadImg ? false : true
					})
				},
				deep: true
			}
		}
	}
</script>

<style lang="scss" scoped>
	@import "grounding.scss";

	.custom-style {
		width: 150rpx;
		font-size: 26rpx;
		background-color: #f56c6c;
		color: #fff;
		margin: 0;
	}
</style>